import { StyleSheet, Text, View, Image, Pressable, TouchableOpacity } from 'react-native';
import React, { useState, useEffect, useRef } from 'react';
import { useNavigation } from '@react-navigation/native';
import { useTranslation } from 'react-i18next';
import { onePx, px2dp, scale } from '~/utils/px2dp';
import { DialogModal, MyLoading } from '~/components';
import { setLaserTimeOut, setLaserTreatmentParameters, LaserTreatmentInterval } from '~/utils/ble/application';
import { startCourse, pauseCourse, getUserCourse, switchCourse } from '~/utils/course';
import { appStore, deviceStore, observer, webSocketStore } from '~/store';
import { useTimeout } from '~/common';

type Type = 'remote' | 'normal';
interface Props {
    type: Type;
    subDevice_sn: string;
    device_sn: string;
    pupillus_mobile: string;
    course: any;
    allStatus: number;
    onRefresh: Function;
}

const MyCourseItem = observer((props: Props) => {
    const { t } = useTranslation();
    const { writeCourseStatus, courseIntervalStatus } = deviceStore.course;
    const { linkSubDeviceStatus } = webSocketStore;
    const [isTimeout, startTimer, resetTimer] = useTimeout(10); // 获取超时相关
    const loadingRef = useRef<any>();
    const { type, subDevice_sn, pupillus_mobile, course, allStatus, onRefresh, device_sn } = props;
    const params = { type, subDevice_sn, device_sn, pupillus_mobile };
    const [visible, setVisible] = useState(false);
    const navigation: any = useNavigation();
    const [workDays, setWorkDays] = useState(0);
    // 疗程详情
    const courseDetailes = (item) => {
        navigation.navigate('MyCourseDetailes', {
            device_sn: subDevice_sn,
            user_course_id: item?.courseid,
            pupillus_mobile,
            type: 1,
        });
    };
    const [actionType, setActionType] = useState('start');
    const [courseInfo, setCourseInfo] = useState<any>({});

    const openModal = (res, action) => {
        setCourseInfo(res);
        setVisible(true);
        setActionType(action);
    };
    const showToast = (title) => {
        Toast.show({ content: title });
    };

    const onConfirm = async () => {
        if (linkSubDeviceStatus == 0 && deviceStore.device.connectedDeviceStatus == 0) {
            Toast.show({ content: t('MyCourseItem.t18') });
            setVisible(false);
            return;
        }
        try {
            const { status, laserParams } = await getUserCourse(courseInfo.id, subDevice_sn, pupillus_mobile);
            loadingRef.current.showLoading();
            startTimer();
            if (actionType === 'stop') {
                await handleStopCourse(laserParams);
            } else if (actionType === 'start') {
                // 开启或者切换
                await handleStartCourse(status, laserParams);
            } else {
                await handSwitchCourse(status, laserParams);
            }
        } catch (error) {
            showToast(t('MyCourseItem.t19'));
        } finally {
            setVisible(false);
        }
    };

    // 暂停疗程
    const handleStopCourse = async (laserParams) => {
        setWorkDays(laserParams.periodic);
        setLaserTimeOut(0, params);
        const requestParams = {
            user_course_id: courseInfo.id,
            device_sn: subDevice_sn,
            mobile: pupillus_mobile,
            type: 1,
            course_id: '',
        };
        try {
            const result = await pauseCourse(requestParams);
            showToast(result.status === 1 ? result.msg : t('MyCourseItem.t20'));
            result.status === 1 && onRefresh && onRefresh();
            loadingRef.current.hideLoading();
            resetTimer();
        } catch (error) {
            loadingRef.current.hideLoading();
            resetTimer();
            showToast(t('MyCourseItem.t20'));
        }
    };
    // 开启疗程
    const handleStartCourse = async (status, laserParams) => {
        if (status === 1) {
            setLaserTreatmentParameters(laserParams, params);
        } else {
            showToast(t('MyCourseItem.t21'));
        }
    };
    // 切换疗程
    const handSwitchCourse = async (status, laserParams) => {
        if (status === 1) {
            setLaserTreatmentParameters(laserParams, params);
        } else {
            showToast(t('MyCourseItem.t21'));
        }
    };
    useEffect(() => {
        if (writeCourseStatus) {
            deviceStore.course.writeCourseStatus = false;
            LaserTreatmentInterval(workDays, params);
        }
    }, [writeCourseStatus]);

    const start = async () => {
        const requestParams = {
            user_course_id: courseInfo.id,
            device_sn: subDevice_sn,
            mobile: pupillus_mobile,
            type: 1,
        };
        try {
            const result = await startCourse(requestParams);
            showToast(result.status == 1 ? t('MyCourseItem.t22') : result.msg);
            onRefresh && onRefresh();
            loadingRef.current.hideLoading();
            resetTimer();
        } catch (error) {
            loadingRef.current.hideLoading();
            resetTimer();
            showToast(t('MyCourseItem.t23'));
        }
    };

    // 切换疗程
    const switchCourseParams = async () => {
        const requestParams = {
            user_course_id: courseInfo.id,
            device_sn: subDevice_sn,
            mobile: pupillus_mobile,
            type: 1,
            course_id: courseInfo.course_id || '',
        };
        try {
            const result = await switchCourse(requestParams);
            showToast(result.status == 1 ? t('MyCourseItem.t24') : result.msg);
            onRefresh && onRefresh();
            loadingRef.current.hideLoading();
            resetTimer();
        } catch (error) {
            loadingRef.current.hideLoading();
            resetTimer();
            showToast(t('MyCourseItem.t25'));
        }
    };

    useEffect(() => {
        if (isTimeout) {
            Toast.show({ content: t('MyCourseItem.t26') });
            loadingRef.current.hideLoading();
            resetTimer();
            deviceStore.course.courseIntervalStatus = false;
            deviceStore.course.writeCourseStatus = false;
        }
    }, [isTimeout]);

    useEffect(() => {
        if (courseIntervalStatus && courseInfo?.id) {
            setLaserTimeOut(1, params);
            deviceStore.course.courseIntervalStatus = false;
            if (actionType == 'start') {
                start();
            } else {
                switchCourseParams();
            }
        }
    }, [courseIntervalStatus, courseInfo?.id, actionType]);

    return (
        <View style={[styles.list_item]}>
            <View style={styles.row}>
                {course.title_img && <Image style={styles.course_image} source={{ uri: course.title_img }} />}
                <View style={course.title_img && { marginLeft: px2dp(24) }}>
                    <View style={styles.row}>
                        <Text style={styles.course_name}>
                            {appStore.app.language == 'zh'
                                ? course.name
                                : course.en_name
                                ? course.en_name
                                : course.name}
                        </Text>
                    </View>
                    <Text style={styles.num}>
                        {t('MyCourseItem.t1')}：{course.list.length}
                        {t('MyCourseItem.t2')}
                    </Text>
                    <Text style={styles.num}>
                        {t('MyCourseItem.t3')}：
                        <Text style={styles.day}>
                            {course.total_day - course.use_day}
                            {t('MyCourseItem.t8')}
                        </Text>
                    </Text>
                </View>
            </View>
            <View>
                {course?.list?.map((item, index) => {
                    return (
                        <View key={index} style={[styles.list_course, styles.row]}>
                            <View style={styles.row}>
                                <Image
                                    source={{ uri: item.course_img ? item.course_img : '' }}
                                    style={styles.course_image}
                                />
                                <View style={[styles.info]}>
                                    <View style={styles.row}>
                                        <Text numberOfLines={1} style={styles.course_name1}>
                                            {appStore.app.language == 'zh'
                                                ? item.courseName
                                                : item.en_course_name
                                                ? item.en_course_name
                                                : item.courseName}
                                        </Text>
                                        {/* <View style={styles.tag}>
                                            <Text style={styles.tagText}>{item.title_tip}</Text>
                                        </View> */}
                                        {item.useState == '1' && (
                                            <View style={[styles.tag, { backgroundColor: '#25C4CD' }]}>
                                                <Text style={styles.tagText}>{t('MyCourseItem.t4')}</Text>
                                            </View>
                                        )}
                                        {item.useState == '3' && (
                                            <View style={styles.tag}>
                                                <Text style={styles.tagText}>{t('MyCourseItem.t5')}</Text>
                                            </View>
                                        )}
                                    </View>
                                    <Text style={styles.num}>
                                        {item.course_title_id !== '0' ? t('MyCourseItem.t6') : t('MyCourseItem.t7')}
                                        <Text style={styles.day}>
                                            {item.course_title_id !== '0' ? item.use_day : item.remainingDays}{' '}
                                            {t('MyCourseItem.t8')}
                                        </Text>
                                    </Text>

                                    <Pressable onPress={() => courseDetailes(item)}>
                                        <Text style={styles.couseDetailes}>
                                            {t('MyCourseItem.t9')} {'>'}
                                        </Text>
                                    </Pressable>
                                </View>
                            </View>
                            {/* 按钮 */}
                            <View>
                                {item.useState == 2 && allStatus == 2 && (
                                    <TouchableOpacity style={styles.start} onPress={() => openModal(item, 'start')}>
                                        <Text style={styles.start_text}>{t('MyCourseItem.t10')}</Text>
                                    </TouchableOpacity>
                                )}
                                {item.useState == 1 && allStatus == 1 && (
                                    <TouchableOpacity style={styles.stop} onPress={() => openModal(item, 'stop')}>
                                        <Text style={styles.stopText}>{t('MyCourseItem.t11')}</Text>
                                    </TouchableOpacity>
                                )}
                                {item.useState == 2 && allStatus == 1 && (
                                    <TouchableOpacity style={styles.start} onPress={() => openModal(item, 'switch')}>
                                        <Text style={styles.start_text}>{t('MyCourseItem.t12')}</Text>
                                    </TouchableOpacity>
                                )}
                            </View>
                        </View>
                    );
                })}
            </View>
            <MyLoading ref={loadingRef} title={t('MyCourseItem.t13')} />
            <DialogModal
                visible={visible}
                onCancel={() => setVisible(false)}
                onConfirm={onConfirm}
                content={`${t('MyCourseItem.t14')}${
                    actionType == 'stop'
                        ? t('MyCourseItem.t15')
                        : actionType == 'switch'
                        ? t('MyCourseItem.t16')
                        : t('MyCourseItem.t17')
                }${
                    appStore.app.language == 'zh'
                        ? courseInfo.courseName
                        : courseInfo.en_course_name
                        ? courseInfo.en_course_name
                        : courseInfo.courseName
                }?`}
            />
        </View>
    );
});
export default MyCourseItem;

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    list_item: {
        backgroundColor: '#fff',
        marginTop: px2dp(24),
        padding: px2dp(12),
        borderRadius: px2dp(20),
    },
    course_image: {
        width: px2dp(60),
        height: px2dp(60),
    },
    course_name: {
        fontWeight: 'bold',
        fontSize: scale(28),
        color: '#191919',
        marginRight: px2dp(20),
        width: '94%',
        lineHeight: px2dp(40),
    },
    num: {
        color: '#a4a4a4',
        fontSize: scale(26),
        marginTop: px2dp(10),
    },
    day: {
        color: '#1877FF',
        fontSize: scale(28),
    },
    list_course: {
        marginTop: px2dp(32),
        justifyContent: 'space-between',
        borderTopWidth: onePx,
        paddingTop: px2dp(24),
        borderColor: '#eee',
    },
    info: {
        marginLeft: px2dp(32),
        width: '60%',
    },
    course_name1: {
        fontSize: scale(26),
    },
    tag: {
        backgroundColor: '#FF6430',
        justifyContent: 'center',
        alignItems: 'center',
        paddingVertical: px2dp(4),
        paddingHorizontal: px2dp(8),
        borderRadius: px2dp(6),
        marginLeft: px2dp(12),
    },
    tagText: {
        color: '#fff',
        fontSize: scale(22),
    },
    couseDetailes: {
        color: '#a4a4a4',
        marginTop: px2dp(12),
        fontSize: scale(24),
    },
    start: {
        backgroundColor: '#1877FF',
        justifyContent: 'center',
        alignItems: 'center',
        width: px2dp(120),
        height: px2dp(48),
        borderRadius: px2dp(30),
        marginTop: px2dp(64),
    },
    start_text: {
        color: '#fff',
        fontSize: scale(24),
    },
    stop: {
        borderWidth: px2dp(2),
        borderColor: '#1877FF',
        justifyContent: 'center',
        alignItems: 'center',
        width: px2dp(120),
        height: px2dp(48),
        borderRadius: px2dp(30),
        marginTop: px2dp(64),
    },
    stopText: {
        color: '#1877FF',
        fontSize: scale(24),
    },
});
